public static UIImage Blur(this UIImage image, float radius) { if (image == null) return image; try { var imageToBlur = CIImage.FromCGImage(image.CGImage); if(imageToBlur == null) return image; var transform = new CIAffineClamp(); transform.Transform = CGAffineTransform.MakeIdentity(); transform.Image = imageToBlur; var gaussianBlurFilter = new CIGaussianBlur(); gaussianBlurFilter.Image = transform.OutputImage; gaussianBlurFilter.Radius = radius; if (context == null) context = CIContext.FromOptions(null); var resultImage = gaussianBlurFilter.OutputImage; var finalImage = UIImage.FromImage(context.CreateCGImage(resultImage, new RectangleF(PointF.Empty, image.Size)), 1, UIImageOrientation.Up); return finalImage; } catch (Exception ex) { Console.WriteLine(ex); return image; } }
public static NSData GetJpegRepresentation (this CIImage image, float compressionQuality) { if (ciContext == null) { var eaglContext = new EAGLContext (EAGLRenderingAPI.OpenGLES2); ciContext = CIContext.FromContext (eaglContext); } using (CGImage outputImageRef = ciContext.CreateCGImage (image, image.Extent)) { using (UIImage uiImage = UIImage.FromImage (outputImageRef, 1f, UIImageOrientation.Up)) { return uiImage.AsJPEG (compressionQuality); } } }
/// <summary> /// Constructs an instance of ImageFilter. /// Newer iOS devices and versions can use GPU to render images and is much faster than using CPU. /// However, some older devices and/or iOS versions (specifically iPad 1 on iOS 5.x) /// may not be able to use GPU and needs to use the CPU. In that case, set the useGPU flag to false. /// </summary> /// <param name='useGPU'> /// useGPU true indicates to use GPU to render images; false indicates to use CPU. /// </param> public ImageFilter(bool useGPU = true) { if (useGPU) { EAGLContext eaglContext = new EAGLContext(EAGLRenderingAPI.S2); Dictionary<object, object> opts = new Dictionary<object, object>(); opts[CIContext.kCIContextWorkingColorSpace] = NSNull.Null(); _ciContext = CIContext.Context(eaglContext, opts); } else { _ciContext = CIContext.Context((Dictionary<object, object>) null); } }
public List <Solution> GetSolutionPatches(string uniqueName) { Solution parent = GetSolution(uniqueName, new ColumnSet()); if (parent is null) { throw new Exception(string.Format("{0} solution can't be found", uniqueName)); } Logger.LogVerbose("Retrieving patches for solution {0}", uniqueName); using (var context = new CIContext(OrganizationService)) { var query = from s in context.SolutionSet where s.ParentSolutionId.Id == parent.Id orderby s.Version descending select s; List <Solution> solutions = query.ToList <Solution>(); return(solutions); } }
private static UIImage BlurImage(UIImage image, int blurRadius) { var beginImage = new CIImage(image); var blur = new CIGaussianBlur { Image = beginImage, Radius = blurRadius }; var outputImage = blur.OutputImage; var context = CIContext.FromOptions(new CIContextOptions() { UseSoftwareRenderer = true }); // Orignal ////var cgImage = context.CreateCGImage( ////outputImage, ////new CGRect(new CGPoint(0, 0), image.Size)); // Modified var cgImage = context.CreateCGImage( outputImage, new CGRect(new CGPoint(blurRadius, -blurRadius), image.Size)); var newImage = UIImage.FromImage(cgImage); // Clear up resources. beginImage = null; context = null; blur = null; outputImage = null; cgImage = null; return(newImage); }
public override void ViewDidLoad () { base.ViewDidLoad (); // Setup collection view CollectionView.AlwaysBounceHorizontal = true; CollectionView.AllowsMultipleSelection = false; CollectionView.AllowsSelection = true; FetchAvailableFilters (); ciContext = CIContext.FromOptions (null); // Add the background image and UIEffectView for the blur UIVisualEffectView effectView = new UIVisualEffectView (UIBlurEffect.FromStyle (UIBlurEffectStyle.Dark)); effectView.TranslatesAutoresizingMaskIntoConstraints = false; View.InsertSubviewAbove (effectView, BackgroundImageView); var views = NSDictionary.FromObjectAndKey (effectView, new NSString ("effectView")); View.AddConstraints (NSLayoutConstraint.FromVisualFormat ("V:|[effectView]|", (NSLayoutFormatOptions)0, null, views)); View.AddConstraints (NSLayoutConstraint.FromVisualFormat ("H:|[effectView]|", (NSLayoutFormatOptions)0, null, views)); }
protected override void ProcessRecord() { base.ProcessRecord(); base.WriteVerbose("Executing CloneAsSolutionRequest"); using (var context = new CIContext(OrganizationService)) { if (string.IsNullOrEmpty(VersionNumber)) { var solution = (from sol in context.SolutionSet where sol.UniqueName == ParentSolutionUniqueName select new Solution { Version = sol.Version }).FirstOrDefault(); if (solution == null || string.IsNullOrEmpty(solution.Version)) { throw new Exception(string.Format("Parent solution with unique name {0} not found.", ParentSolutionUniqueName)); } string[] versions = solution.Version.Split('.'); char dot = '.'; VersionNumber = string.Concat(versions[0], dot, Convert.ToInt32(versions[1]) + 1, dot, versions[2], dot, versions[3]); base.WriteVerbose(string.Format("New version number {0}", VersionNumber)); } var cloneAsPatch = new CloneAsSolutionRequest { DisplayName = DisplayName, ParentSolutionUniqueName = ParentSolutionUniqueName, VersionNumber = VersionNumber, }; OrganizationService.Execute(cloneAsPatch); } base.WriteVerbose("Completed CloneAsSolutionRequest"); }
public void CreateRefCount() { // Bug #7117 CIImage img = new CIImage(CIColor.FromRgb(0.5f, 0.5f, 0.5f)); Selector retainCount = new Selector("retainCount"); using (var ctx = CIContext.Create()) { using (var v = ctx.CreateCGImage(img, new RectangleF(0, 0, 5, 5))) { int rc = Messaging.int_objc_msgSend(v.Handle, retainCount.Handle); Assert.AreEqual(1, rc, "CreateCGImage #a1"); } using (var v = ctx.CreateCGImage(img, new RectangleF(0, 0, 32, 32), CIImage.FormatARGB8, null)) { int rc = Messaging.int_objc_msgSend(v.Handle, retainCount.Handle); Assert.AreEqual(1, rc, "CreateCGImage #b1"); } using (var v = ctx.CreateCGImage(img, new RectangleF(0, 0, 5, 5), CIFormat.ARGB8, null)) { int rc = Messaging.int_objc_msgSend(v.Handle, retainCount.Handle); Assert.AreEqual(1, rc, "CreateCGImage #c1"); } } }
protected override void ProcessRecord() { base.ProcessRecord(); base.WriteVerbose(string.Format("Updating Solution {0} Version: {1}", SolutionName, Version)); CrmConnection connection = CrmConnection.Parse(connectionString); Solution solution = null; using (OrganizationService orgService = new OrganizationService(connection)) { using (CIContext context = new CIContext(orgService)) { var query = from s in context.SolutionSet where s.UniqueName == solutionName select s; solution = query.FirstOrDefault <Solution>(); } if (solution == null) { throw new Exception(string.Format("Solution {0} could not be found", SolutionName)); } else { Solution update = new Solution(); update.Id = solution.Id; update.Version = version; orgService.Update(update); base.WriteVerbose(string.Format("Solution {0} Update to Version: {1}", SolutionName, Version)); } } }
protected override void ProcessRecord() { base.ProcessRecord(); base.WriteVerbose(string.Format("Removing Solution Components: {0}", SolutionName)); using (var context = new CIContext(OrganizationService)) { var query1 = from solution in context.SolutionSet where solution.UniqueName == SolutionName select solution.Id; if (query1 == null) { throw new Exception(string.Format("Solution {0} could not be found", SolutionName)); } var solutionId = query1.FirstOrDefault(); var query = from s in context.SolutionComponentSet where s.SolutionId == new EntityReference(Solution.EntityLogicalName, solutionId) && s.RootSolutionComponentId == null select new { s.ComponentType, s.ObjectId }; foreach (var solutionComponent in query.ToList()) { var removeReq = new RemoveSolutionComponentRequest() { ComponentId = (Guid)solutionComponent.ObjectId, ComponentType = (int)solutionComponent.ComponentType.Value, SolutionUniqueName = SolutionName }; OrganizationService.Execute(removeReq); base.WriteVerbose(string.Format("Removed component from solution with Id : {0} and Type: {1}", solutionComponent.ObjectId, solutionComponent.ComponentType.Value)); } } }
public static void DrawWithColorTransform(this NSView view, Color?color, Action drawDelegate) { if (color.HasValue) { if (view.Frame.Size.Width <= 0 || view.Frame.Size.Height <= 0) { return; } // render view to image var image = new NSImage(view.Frame.Size); image.LockFocusFlipped(!view.IsFlipped); drawDelegate(); image.UnlockFocus(); // create Core image for transformation var rr = new RectangleF(0, 0, view.Frame.Size.Width, view.Frame.Size.Height); var ciImage = CIImage.FromCGImage(image.AsCGImage(ref rr, NSGraphicsContext.CurrentContext, null)); // apply color matrix var transformColor = new CIColorMatrix(); transformColor.SetDefaults(); transformColor.Image = ciImage; transformColor.RVector = new CIVector(0, (float)color.Value.Red, 0); transformColor.GVector = new CIVector((float)color.Value.Green, 0, 0); transformColor.BVector = new CIVector(0, 0, (float)color.Value.Blue); ciImage = (CIImage)transformColor.ValueForKey(new NSString("outputImage")); var ciCtx = CIContext.FromContext(NSGraphicsContext.CurrentContext.GraphicsPort, null); ciCtx.DrawImage(ciImage, rr, rr); } else { drawDelegate(); } }
private void VerifyUpgrade() { string upgradeName = UniqueSolutionName + "_Upgrade"; base.WriteVerbose(string.Format("Retrieving Solution: {0}", upgradeName)); using (var context = new CIContext(OrganizationService)) { var query = from s in context.SolutionSet where s.UniqueName == upgradeName select s; Solution solution = query.FirstOrDefault(); if (solution != null) { throw new Exception(string.Format("Solution still exists after upgrade: {0}", upgradeName)); } else { base.WriteVerbose(string.Format("Upgrade Solution Merged: {0}", upgradeName)); } } }
public static String[] CalculatePValue(UIImage image, ref nfloat totP, ref nfloat avgP) { UIImage uiImagePic = image; CIContext ctx = CIContext.FromOptions(null); CGImage cgimage = uiImagePic.CGImage; nfloat powerValueAvg = 0.0f; nfloat powerValueTot = 0.0f; nint numPixels = 0; //compute values nint width = cgimage.Width; nint height = cgimage.Height; nint bpr = cgimage.BytesPerRow; nint bpp = cgimage.BitsPerPixel; nint bpc = cgimage.BitsPerComponent; nint bytes_per_pixel = bpp / bpc; CGBitmapFlags info = cgimage.BitmapInfo; CGDataProvider provider = cgimage.DataProvider; NSData data = provider.CopyData(); IntPtr bytesintp = data.Bytes; byte[] bytes = new byte[data.Length]; Marshal.Copy(bytesintp, bytes, 0, (int)data.Length); Console.WriteLine("Pixel Data:"); for (nint row = 0; row < height; row++) { for (nint col = 0; col < width; col++) { byte[] pixel = new byte[bytes_per_pixel]; for (int i = 0; i < bytes_per_pixel; i++) { pixel [i] = bytes [row * bpr + col * bytes_per_pixel + i]; } //Console.Write("("); for (nint x = 0; x < bytes_per_pixel; x++) { //pixel[0] is r //pixel[1] is g //pixel[2] is b //pixel[3] is alpha numPixels++; nfloat curPower = pixel [0] * 0.299f + pixel [1] * 0.587f + pixel [2] * 0.0722f; powerValueTot += curPower; powerValueAvg = powerValueTot / numPixels; // Console.Write(pixel[x]); // if( x < bytes_per_pixel - 1 ) // Console.Write(","); } //Console.Write(")"); //if( col < width - 1 ) // Console.Write(", "); } //Console.Write("\n"); } totP = powerValueTot; avgP = powerValueAvg; string outputToName; outputToName = powerValueAvg.ToString("0.0000"); string outputToName2 = powerValueTot.ToString("0.0000"); string[] strToRet = new string[2]; strToRet [0] = outputToName; strToRet [1] = outputToName2; return(strToRet); }
protected override void ProcessRecord() { base.ProcessRecord(); base.WriteVerbose(string.Format("Exporting Solution: {0}", UniqueSolutionName)); var solutionFile = new StringBuilder(); Solution solution; using (var context = new CIContext(OrganizationService)) { var query = from s in context.SolutionSet where s.UniqueName == UniqueSolutionName select s; solution = query.FirstOrDefault(); } if (solution == null) { throw new Exception(string.Format("Solution {0} could not be found", UniqueSolutionName)); } solutionFile.Append(UniqueSolutionName); if (IncludeVersionInName) { solutionFile.Append("_"); solutionFile.Append(solution.Version.Replace(".", "_")); } if (Managed) { solutionFile.Append("_managed"); } solutionFile.Append(".zip"); var exportSolutionRequest = new ExportSolutionRequest { Managed = Managed, SolutionName = UniqueSolutionName, ExportAutoNumberingSettings = ExportAutoNumberingSettings, ExportCalendarSettings = ExportCalendarSettings, ExportCustomizationSettings = ExportCustomizationSettings, ExportEmailTrackingSettings = ExportEmailTrackingSettings, ExportGeneralSettings = ExportGeneralSettings, ExportIsvConfig = ExportIsvConfig, ExportMarketingSettings = ExportMarketingSettings, ExportOutlookSynchronizationSettings = ExportOutlookSynchronizationSettings, ExportRelationshipRoles = ExportRelationshipRoles, ExportSales = ExportSales, TargetVersion = TargetVersion, ExportExternalApplications = ExportExternalApplications }; var exportSolutionResponse = OrganizationService.Execute(exportSolutionRequest) as ExportSolutionResponse; string solutionFilePath = Path.Combine(OutputFolder, solutionFile.ToString()); File.WriteAllBytes(solutionFilePath, exportSolutionResponse.ExportSolutionFile); base.WriteObject(solutionFile.ToString()); }
protected override void ProcessRecord() { base.ProcessRecord(); base.WriteVerbose("Executing CloneAsPatchRequest"); using (var context = new CIContext(OrganizationService)) { base.WriteVerbose("VersionNumber not supplied. Generating default VersionNumber"); if (string.IsNullOrEmpty(VersionNumber)) { var solution = (from sol in context.SolutionSet where sol.UniqueName == ParentSolutionUniqueName || sol.UniqueName.StartsWith(ParentSolutionUniqueName + "_Patch") orderby sol.Version descending select new Solution { Version = sol.Version, FriendlyName = sol.FriendlyName }).FirstOrDefault(); if (solution == null || string.IsNullOrEmpty(solution.Version)) { throw new Exception(string.Format("Parent solution with unique name {0} not found.", ParentSolutionUniqueName)); } string[] versions = solution.Version.Split('.'); char dot = '.'; VersionNumber = string.Concat(versions[0], dot, versions[1], dot, Convert.ToInt32(versions[2]) + 1, dot, 0); base.WriteVerbose(string.Format("New VersionNumber: {0}", VersionNumber)); } if (string.IsNullOrEmpty(DisplayName)) { var solution = (from sol in context.SolutionSet where sol.UniqueName == ParentSolutionUniqueName select new Solution { FriendlyName = sol.FriendlyName }).FirstOrDefault(); base.WriteVerbose((solution == null).ToString()); base.WriteVerbose(solution.FriendlyName); if (solution == null || string.IsNullOrEmpty(solution.FriendlyName)) { throw new Exception(string.Format("Parent solution with unique name {0} not found.", ParentSolutionUniqueName)); } DisplayName = solution.FriendlyName; } var cloneAsPatch = new CloneAsPatchRequest { DisplayName = DisplayName, ParentSolutionUniqueName = ParentSolutionUniqueName, VersionNumber = VersionNumber, }; CloneAsPatchResponse response = OrganizationService.Execute(cloneAsPatch) as CloneAsPatchResponse; base.WriteVerbose(string.Format("Patch solution created with Id {0}", response.SolutionId)); base.WriteVerbose("Retrieving Patch Name"); var patch = (from sol in context.SolutionSet where sol.Id == response.SolutionId select new Solution { UniqueName = sol.UniqueName }).FirstOrDefault(); if (patch == null || string.IsNullOrEmpty(patch.UniqueName)) { throw new Exception(string.Format("Solution with Id {0} not found.", response.SolutionId)); } base.WriteVerbose(string.Format("Patch solution name: {0}", patch.UniqueName)); base.WriteObject(patch.UniqueName); } base.WriteVerbose("Completed CloneAsPatchRequest"); }
private void InitializeImagingContext() { #if MONOTOUCH if (ciContext == null) ciContext = CIContext.FromOptions(null); #else if (ciContext == null) ciContext = CIContext.FromContext (context); #endif }
public override void ViewDidLoad() { base.ViewDidLoad(); btnTrigger.Hidden = false; bekerImage = UIImage.FromFile("bekerDicht.jpg"); imvDisplayChoice.Image = bekerImage; colorContrast = new CIColorControls() { Image = CIImage.FromCGImage(bekerImage.CGImage), }; int count = 0; //default contrast waarde is 1 colorContrast.Contrast = 1; btnUnPushedTimer = NSTimer.CreateRepeatingScheduledTimer(TimeSpan.FromSeconds(1.0), delegate { count++; Console.WriteLine(colorContrast.Contrast); Console.WriteLine(count); if (count <= 6) { colorContrast.Contrast += 0.1f; Console.WriteLine("increase"); } else if (count <= 12) { colorContrast.Contrast -= 0.1f; Console.WriteLine("decrease"); } else { count = 0; } var output = colorContrast.OutputImage; var context = CIContext.FromOptions(null); var result = context.CreateCGImage(output, output.Extent); imvDisplayChoice.Image = UIImage.FromImage(result); }); //een plaatje wisselt met contrast van laag naar hoog en weer terug. //als het contrast van laag naar hoog gaat hoor je een geluidje! (slurp geluid) btnTrigger.TouchUpInside += (sender, e) => { //De knop word hidden btnTrigger.Hidden = true; //als er op de knop gedrukt is gaat het contrast om hoog en blijft het plaatje staan in het hoogste contrast. //tegelijker tijd word de keuze uit gesprooken //als de keuze uit gesprooken is word het scherm voor 5 seconde zwart (zo donker mogelijk). }; }
public RegisterController(CIContext context, IConfiguration config) { _config = config; _context = context; }
protected override void ProcessRecord() { base.ProcessRecord(); WriteVerbose("Plugin Registration intiated"); if (UseSplitAssembly) { if (!File.Exists(ProjectFilePath)) { throw new Exception("Project File Path is required if you want to split assembly."); } if (RegistrationType == RegistrationTypeEnum.Delsert) { throw new Exception("Registration type 'Remove Plugin Types and Steps which are not in mapping and Upsert' will not work when 'Split Assembly' is enabled."); } if (!File.Exists(MappingFile)) { throw new Exception("Mapping Json Path is required if you want to split assembly."); } } var assemblyInfo = AssemblyInfo.GetAssemblyInfo(AssemblyPath); WriteVerbose($"Assembly Name: {assemblyInfo.AssemblyName}"); WriteVerbose($"Assembly Version: {assemblyInfo.Version}"); using (var context = new CIContext(OrganizationService)) { var pluginRegistrationHelper = new PluginRegistrationHelper(OrganizationService, context, WriteVerbose, WriteWarning); WriteVerbose("PluginRegistrationHelper intiated"); Assembly pluginAssembly = null; Guid pluginAssemblyId = Guid.Empty; if (File.Exists(MappingFile)) { pluginAssembly = ReadMappingFile(); pluginAssemblyId = pluginAssembly.Id ?? Guid.Empty; } else { pluginAssemblyId = pluginRegistrationHelper.UpsertPluginAssembly(pluginAssembly, assemblyInfo, SolutionName, RegistrationType); WriteVerbose($"UpsertPluginAssembly {pluginAssemblyId} completed"); WriteVerbose("Plugin Registration completed"); return; } if (pluginAssembly == null) { WriteVerbose("Plugin Registration completed"); return; } if (pluginAssembly.PluginTypes == null) { WriteVerbose("No mapping found for types."); WriteVerbose("Plugin Registration completed"); return; } if (RegistrationType == RegistrationTypeEnum.Delsert) { WriteVerbose($"RemoveComponentsNotInMapping {assemblyInfo.AssemblyName} started"); pluginRegistrationHelper.RemoveComponentsNotInMapping(pluginAssembly); WriteVerbose($"RemoveComponentsNotInMapping {assemblyInfo.AssemblyName} completed"); RegistrationType = RegistrationTypeEnum.Upsert; } if (UseSplitAssembly) { foreach (var type in pluginAssembly.PluginTypes) { UploadSplitAssembly(assemblyInfo, pluginRegistrationHelper, type); } } else { WriteVerbose($"UpsertPluginAssembly {pluginAssemblyId} started"); pluginAssemblyId = pluginRegistrationHelper.UpsertPluginAssembly(pluginAssembly, assemblyInfo, SolutionName, RegistrationType); WriteVerbose($"UpsertPluginAssembly {pluginAssemblyId} completed"); foreach (var type in pluginAssembly.PluginTypes) { pluginRegistrationHelper.UpsertPluginTypeAndSteps(pluginAssemblyId, type, SolutionName, RegistrationType); } } } WriteVerbose("Plugin Registration completed"); }
void CameraImageCaptured(object sender, UIImagePickerMediaPickedEventArgs e) { bool result = false; string imagePath = null; // create a url of the path for the file to write NSUrl imageDestUrl = NSUrl.CreateFileUrl(new string[] { ImageDest }); // create a CGImage destination that converts the image to jpeg CGImageDestination cgImageDest = CGImageDestination.Create(imageDestUrl, MobileCoreServices.UTType.JPEG, 1); if (cgImageDest != null) { // note: the edited image is saved "correctly", so we don't have to rotate. // rotate the image 0 degrees since we consider portrait to be the default position. CIImage ciImage = new CIImage(e.OriginalImage.CGImage); float rotationDegrees = 0.00f; switch (e.OriginalImage.Orientation) { case UIImageOrientation.Up: { // don't do anything. The image space and the user space are 1:1 break; } case UIImageOrientation.Left: { // the image space is rotated 90 degrees from user space, // so do a CCW 90 degree rotation rotationDegrees = 90.0f; break; } case UIImageOrientation.Right: { // the image space is rotated -90 degrees from user space, // so do a CW 90 degree rotation rotationDegrees = -90.0f; break; } case UIImageOrientation.Down: { rotationDegrees = 180; break; } } // create our transform and apply it to the image CGAffineTransform transform = CGAffineTransform.MakeIdentity( ); transform.Rotate(rotationDegrees * Rock.Mobile.Math.Util.DegToRad); CIImage rotatedImage = ciImage.ImageByApplyingTransform(transform); // create a context and render it back out to a CGImage. (Cast to ints so we account for any floating point error) CIContext ciContext = CIContext.FromOptions(null); CGImage rotatedCGImage = ciContext.CreateCGImage(rotatedImage, new System.Drawing.RectangleF((int)rotatedImage.Extent.X, (int)rotatedImage.Extent.Y, (int)rotatedImage.Extent.Width, (int)rotatedImage.Extent.Height)); // put the image in the destination, converting it to jpeg. cgImageDest.AddImage(rotatedCGImage); // close and dispose. if (cgImageDest.Close( )) { result = true; imagePath = ImageDest; cgImageDest.Dispose( ); } } CameraFinishedCallback(result, imagePath); }
void UpdateImage(bool coalesce, bool animate) { if (!TryInit(animate)) { return; } if (filtering) { needsFilter = true; return; } if (image == null) { return; } var blurFilter = (BlurFilter)GetFilter(BlurFilter.Key); var modifyFilter = (ModifyFilter)GetFilter(ModifyFilter.Key); bool dirty = blurFilter != null ? blurFilter.Dirty : false; dirty |= modifyFilter != null ? modifyFilter.Dirty : false; filtering = true; TryStartIndicatorForFilter(); Action runFilters = () => { var filterInput = new CIImage(image.CGImage); CIImage filteredCIImage = Apply(blurFilter, filterInput, dirty); filterInput = filteredCIImage ?? new CIImage(image.CGImage); filteredCIImage = Apply(modifyFilter, filterInput, dirty) ?? filteredCIImage; CGImage cgFilteredImage = null; if (filteredCIImage != null) { CIContext context = CIContext.FromOptions(new CIContextOptions { UseSoftwareRenderer = false }); cgFilteredImage = context.CreateCGImage(filteredCIImage, filteredCIImage.Extent); } if (coalesce) { InvokeOnMainThread(() => Apply(cgFilteredImage, image, dirty)); } else { Apply(cgFilteredImage, image, dirty); } }; if (coalesce) { Task.Delay(250).ContinueWith(_ => runFilters()); } else { runFilters(); } blurFilter.Dirty = modifyFilter.Dirty = false; }
protected override void ProcessRecord() { base.ProcessRecord(); base.WriteVerbose(string.Format("Updating Web Resource: {0}", Path)); base.WriteVerbose(string.Format("Solution Id: {0}", SolutionId)); FileInfo webResourceInfo = new FileInfo(Path); String content = Convert.ToBase64String(File.ReadAllBytes(Path)); Guid resourceId; using (var context = new CIContext(OrganizationService)) { if (String.IsNullOrEmpty(UniqueName)) { var query = from a in context.WebResourceSet where a.Name == System.IO.Path.GetFileNameWithoutExtension(webResourceInfo.Name) select new WebResource { Name = a.Name, Id = a.Id }; if (!SolutionId.Equals(Guid.Empty)) { query = from a in context.WebResourceSet join sol in context.SolutionComponentSet on a.Id equals sol.ObjectId where a.Name.Contains(System.IO.Path.GetFileNameWithoutExtension(webResourceInfo.Name)) && sol.SolutionId.Equals(SolutionId) select new WebResource { Name = a.Name, Id = a.Id }; } List <WebResource> resources = new List <WebResource>(); if (!string.IsNullOrEmpty(RegExToMatchUniqueName)) { base.WriteVerbose(string.Format("Searching Web Resource with RegEx: {0}", RegExToMatchUniqueName)); Regex rgx = new Regex(RegExToMatchUniqueName, RegexOptions.IgnoreCase); resources = (from a in query.ToList() where rgx.IsMatch(a.Name) select new WebResource { Name = a.Name, Id = a.Id }).ToList(); } else { resources = query.ToList(); } if (resources.Count != 1) { throw new ItemNotFoundException(string.Format("{0} web resources found matching file name", resources.Count)); } else { resourceId = resources[0].Id; UniqueName = resources[0].Name; } } else { var query = from a in context.WebResourceSet where a.Name == UniqueName select a.Id; resourceId = query.FirstOrDefault(); if (resourceId == null || resourceId == Guid.Empty) { throw new ItemNotFoundException(string.Format("{0} was not found", UniqueName)); } } WebResource webResource = new WebResource() { Id = resourceId, Content = content }; OrganizationService.Update(webResource); WriteObject(resourceId); base.WriteVerbose(string.Format("Web Resource Updated Name: {0}", UniqueName)); if (Publish) { base.WriteVerbose(string.Format("Publishing Web Resource: {0}", UniqueName)); PublishXmlRequest req = new PublishXmlRequest() { ParameterXml = string.Format("<importexportxml><webresources><webresource>{0}</webresource></webresources></importexportxml>", resourceId) }; OrganizationService.Execute(req); base.WriteVerbose(string.Format("Published Web Resource: {0}", UniqueName)); } } }
// On load, construct the CIRawFilter public override void ViewDidLoad () { base.ViewDidLoad (); var asset = Asset; if (asset == null) return; // Setup options to request original image. var options = new PHImageRequestOptions { Version = PHImageRequestOptionsVersion.Original, Synchronous = true }; // Request the image data and UTI type for the image. PHImageManager.DefaultManager.RequestImageData (asset, options, (imageData, dataUTI, _, __) => { if (imageData == null || dataUTI == null) return; // Create a CIRawFilter from original image data. // UTI type is passed in to provide the CIRawFilter with a hint about the UTI type of the Raw file. //var rawOptions = [String (kCGImageSourceTypeIdentifierHint) : dataUTI ] var rawOptions = new NSMutableDictionary (); var imageIOLibrary = Dlfcn.dlopen ("/System/Library/Frameworks/ImageIO.framework/ImageIO", 0); var key = Dlfcn.GetIntPtr (imageIOLibrary, "kCGImageSourceTypeIdentifierHint"); rawOptions.LowlevelSetObject (dataUTI, key); ciRawFilter = CIFilter.CreateRawFilter (imageData, rawOptions); if (ciRawFilter == null) return; // Get the native size of the image produced by the CIRawFilter. var sizeValue = ciRawFilter.ValueForKey (Keys.kCIOutputNativeSizeKey) as CIVector; if (sizeValue != null) imageNativeSize = new CGSize (sizeValue.X, sizeValue.Y); // Record the original value of the temperature, and setup the editing slider. var tempValue = (NSNumber)ciRawFilter.ValueForKey (Keys.kCIInputNeutralTemperatureKey); if (tempValue != null) { originalTemp = tempValue.FloatValue; TempSlider.SetValue (tempValue.FloatValue, animated: false); } // Record the original value of the tint, and setup the editing slider. var tintValue = (NSNumber)ciRawFilter.ValueForKey (Keys.kCIInputNeutralTintKey); if (tintValue != null) { originalTint = tintValue.FloatValue; TintSlider.SetValue (tintValue.FloatValue, animated: false); } }); // Create EAGL context used to render the CIImage produced by the CIRawFilter to display. ImageView.Context = new EAGLContext (EAGLRenderingAPI.OpenGLES3); ciContext = CIContext.FromContext (ImageView.Context, new CIContextOptions { CIImageFormat = CIImage.FormatRGBAh }); }
UIImage CropImage(UIImage sourceImage, CGRect cropDimension) { // step one, transform the crop region into image space. // (So pixelX is a pixel in the actual image, not the scaled screen) // convert our position on screen to where it should be in the image float pixelX = (float)(cropDimension.X * ScreenToImageScalar); float pixelY = (float)(cropDimension.Y * ScreenToImageScalar); // same for height, since the image was scaled down to fit the screen. float width = (float)cropDimension.Width * ScreenToImageScalar; float height = (float)cropDimension.Height * ScreenToImageScalar; // Now we're going to rotate the image to actually be "up" as the user // sees it. To do that, we simply rotate it according to the apple documentation. float rotationDegrees = 0.0f; switch (sourceImage.Orientation) { case UIImageOrientation.Up: { // don't do anything. The image space and the user space are 1:1 break; } case UIImageOrientation.Left: { // the image space is rotated 90 degrees from user space, // so do a CCW 90 degree rotation rotationDegrees = 90.0f; break; } case UIImageOrientation.Right: { // the image space is rotated -90 degrees from user space, // so do a CW 90 degree rotation rotationDegrees = -90.0f; break; } case UIImageOrientation.Down: { rotationDegrees = 180; break; } } // Now get a transform so we can rotate the image to be oriented the same as when the user previewed it CGAffineTransform fullImageTransform = GetImageTransformAboutCenter(rotationDegrees, sourceImage.Size); // apply to the image CIImage ciCorrectedImage = new CIImage(sourceImage.CGImage); CIImage ciCorrectedRotatedImage = ciCorrectedImage.ImageByApplyingTransform(fullImageTransform); // create a context and render it back out to a CGImage. CIContext ciContext = CIContext.FromOptions(null); CGImage rotatedCGImage = ciContext.CreateCGImage(ciCorrectedRotatedImage, ciCorrectedRotatedImage.Extent); // now the image is properly orientated, so we can crop it. CGRect cropRegion = new CGRect(pixelX, pixelY, width, height); CGImage croppedImage = rotatedCGImage.WithImageInRect(cropRegion); return(new UIImage(croppedImage)); }
protected override void ProcessRecord() { base.ProcessRecord(); base.WriteVerbose(string.Format("Updating Web Resource: {0}", Path)); FileInfo webResourceInfo = new FileInfo(Path); String content = Convert.ToBase64String(File.ReadAllBytes(Path)); Guid resourceId; using (var context = new CIContext(OrganizationService)) { if (String.IsNullOrEmpty(UniqueName)) { var query = from a in context.WebResourceSet where a.Name.Contains(webResourceInfo.Name) select new WebResource { Name = a.Name, Id = a.Id }; var resources = query.ToList <WebResource>(); if (resources.Count != 1) { throw new ItemNotFoundException(string.Format("{0} web resources found matching file name", resources.Count)); } else { resourceId = resources[0].Id; UniqueName = resources[0].Name; } } else { var query = from a in context.WebResourceSet where a.Name == UniqueName select a.Id; resourceId = query.FirstOrDefault(); if (resourceId == null || resourceId == Guid.Empty) { throw new ItemNotFoundException(string.Format("{0} was not found", UniqueName)); } } WebResource webResource = new WebResource() { Id = resourceId, Content = content }; OrganizationService.Update(webResource); WriteObject(resourceId); base.WriteVerbose(string.Format("Web Resource Updated Name: {0}", UniqueName)); if (Publish) { base.WriteVerbose(string.Format("Publishing Web Resource: {0}", UniqueName)); PublishXmlRequest req = new PublishXmlRequest() { ParameterXml = string.Format("<importexportxml><webresources><webresource>{0}</webresource></webresources></importexportxml>", resourceId) }; OrganizationService.Execute(req); base.WriteVerbose(string.Format("Published Web Resource: {0}", UniqueName)); } } }
public StudentsController(CIContext context) { _context = context; }
CIColorControls colorCtrls; //CIFilter void HandleValueChanged (object sender, EventArgs e) { // use the low-res version if (colorCtrls == null) colorCtrls = new CIColorControls () { Image = CIImage.FromCGImage (sourceImage.CGImage) }; else colorCtrls.Image = CIImage.FromCGImage(sourceImage.CGImage); if (context == null) context = CIContext.FromOptions (null); colorCtrls.Brightness = sliderBrightness.Value; colorCtrls.Saturation = sliderSaturation.Value; colorCtrls.Contrast = sliderContrast.Value; using (var outputImage = colorCtrls.OutputImage) { var result = context.CreateCGImage (outputImage, outputImage.Extent); imageView.Image = UIImage.FromImage (result); } }
public Solution CreatePatch(string uniqueName, string versionNumber, string displayName) { using (var context = new CIContext(OrganizationService)) { if (string.IsNullOrEmpty(versionNumber)) { Logger.LogVerbose("VersionNumber not supplied. Generating default VersionNumber"); var solution = (from sol in context.SolutionSet where sol.UniqueName == uniqueName || sol.UniqueName.StartsWith(uniqueName + "_Patch") orderby sol.Version descending select new Solution { Version = sol.Version, FriendlyName = sol.FriendlyName }).FirstOrDefault(); if (solution == null || string.IsNullOrEmpty(solution.Version)) { throw new Exception(string.Format("Parent solution with unique name {0} not found.", uniqueName)); } string[] versions = solution.Version.Split('.'); char dot = '.'; versionNumber = string.Concat(versions[0], dot, versions[1], dot, Convert.ToInt32(versions[2]) + 1, dot, 0); Logger.LogVerbose("New VersionNumber: {0}", versionNumber); } if (string.IsNullOrEmpty(displayName)) { Logger.LogVerbose("displayName not supplied. Generating default DisplayName"); var solution = (from sol in context.SolutionSet where sol.UniqueName == uniqueName select new Solution { FriendlyName = sol.FriendlyName }).FirstOrDefault(); if (solution == null || string.IsNullOrEmpty(solution.FriendlyName)) { throw new Exception(string.Format("Parent solution with unique name {0} not found.", uniqueName)); } displayName = solution.FriendlyName; } var cloneAsPatch = new CloneAsPatchRequest { DisplayName = displayName, ParentSolutionUniqueName = uniqueName, VersionNumber = versionNumber, }; CloneAsPatchResponse response = OrganizationService.Execute(cloneAsPatch) as CloneAsPatchResponse; Logger.LogInformation("Patch solution created with Id {0}", response.SolutionId); Solution patch = GetSolution(response.SolutionId, new ColumnSet(true)); Logger.LogInformation("Patch solution name: {0}", patch.UniqueName); return(patch); } }
public PluginRegistrationHelper(IOrganizationService service, CIContext xrmContext) { this.OrganizationService = service; this.context = xrmContext; }
UIImage AdjustImage(UIImage image) { if (colorCtrls == null) colorCtrls = new CIColorControls () { Image = CIImage.FromCGImage (image.CGImage) }; else colorCtrls.Image = CIImage.FromCGImage(image.CGImage); if (context == null) context = CIContext.FromOptions (null); colorCtrls.Brightness = sliderB.Value; colorCtrls.Saturation = sliderS.Value; colorCtrls.Contrast = sliderC.Value; using (var outputImage = colorCtrls.OutputImage) { var result = context.CreateCGImage (outputImage, outputImage.Extent); return UIImage.FromImage (result); } }
public LoginController(CIContext context, IConfiguration config) { _config = config; _context = context; }
protected override void ProcessRecord() { base.ProcessRecord(); WriteVerbose($"ParameterSetName: {ParameterSetName}"); WriteVerbose($"Id: {Id}"); WriteVerbose($"Name: {Name}"); WriteVerbose($"RoleNames: {RoleNames}"); string filteringKey; string filteringValue; Func <SystemForm, bool> predicateFunction; if (ParameterSetName == findByName) { filteringKey = "name"; filteringValue = Name; predicateFunction = x => x.Name == Name; } else { filteringKey = "id"; filteringValue = Id.ToString(); predicateFunction = x => x.Id == Id; } using (var ctx = new CIContext(OrganizationService)) { List <SystemForm> dashboards; dashboards = ctx.SystemFormSet.Where(predicateFunction).ToList(); if (dashboards.Count == 0) { WriteWarning($"Couldn't find dashboard with {filteringKey} {filteringValue}"); return; } if (dashboards.Count > 1) { WriteWarning($"There are more than one dashboard with name {Name}. Try execute cmdlet using Id."); return; } var dashboard = dashboards.Single(); var roleNamesArray = RoleNames .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries) .Select(x => x.Trim()) .ToArray(); var dashboardName = dashboard.Name; var newFormxml = SetRolesOnFormXml(dashboard.FormXml, roleNamesArray); if (dashboard.FormXml == newFormxml) { WriteVerbose("Exiting without any change.."); return; } WriteVerbose("Saving changes.."); OrganizationService.Update(new SystemForm { Id = dashboard.Id, FormXml = newFormxml }); WriteVerbose("Publishing changes.."); OrganizationService.PublishXml($"<dashboards><dashboard>{dashboard.Id}</dashboard></dashboards>"); } }
/// <summary> /// Gets called by the VideoFrameSamplerDelegate if a new image has been captured. Does the rectangle detection. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">Event arguments</param> void HandleImageCaptured(object sender, ImageCaptureEventArgs e) { // Detect the rectangles in the captured image. // Important: case CGImage to CIImage. There is an implicit cast operator from CGImage to CIImage, but if we // pass the CGImage in to FeaturesInImage(), many many (implicit) CIImage instance will be created because this // method is called very often. The garbage collector cannot keep up with that and we runn out of memory. // By casting manually and using() the CIImage, it will be disposed immediately, freeing up memory. using (CIImage inputCIImage = (CIImage)e.Image) { // Let the detector do its work on the image. var rectangles = detector.FeaturesInImage(inputCIImage); // Find the biggest rectangle. Note: in my tests I have never seen that more than one rectangle would be detected, but better be prepared. nfloat maxWidth = 0f; nfloat maxHeight = 0f; CIRectangleFeature biggestRect = rectangles.Length > 0 ? (CIRectangleFeature)rectangles [0] : null; Console.WriteLine("Found " + rectangles.Length + " rectangles."); foreach (CIRectangleFeature rect in rectangles) { Console.WriteLine("Found rect: " + rect); nfloat minX = (nfloat)Math.Min(rect.TopLeft.X, rect.BottomLeft.X); nfloat minY = (nfloat)Math.Min(rect.TopLeft.Y, rect.TopRight.Y); nfloat maxX = (nfloat)Math.Min(rect.TopRight.X, rect.BottomRight.X); nfloat maxY = (nfloat)Math.Min(rect.BottomLeft.Y, rect.BottomRight.Y); if (maxX - minX > maxWidth && maxY - minY > maxHeight) { maxWidth = maxX - minX; maxHeight = maxY - minY; biggestRect = rect; } } if (biggestRect == null) { this.InvokeOnMainThread(() => { this.imageViewOverlay.Image = null; this.imageViewPerspective.Image = null; }); return; } Console.WriteLine("Highlighting: top left = " + biggestRect.TopLeft + "; top right = " + biggestRect.TopRight + "; bottom left = " + biggestRect.BottomLeft + "; bottom right = " + biggestRect.BottomRight); // We are not on the main thread here. this.InvokeOnMainThread(() => { // Adjust the overlay image to the corners of the detected rectangle with CIPerspectiveTransformWithExtent. using (var dict = new NSMutableDictionary()) { dict.Add(key: new NSString("inputExtent"), value: new CIVector(inputCIImage.Extent)); dict.Add(key: new NSString("inputTopLeft"), value: new CIVector(biggestRect.TopLeft)); dict.Add(key: new NSString("inputTopRight"), value: new CIVector(biggestRect.TopRight)); dict.Add(key: new NSString("inputBottomLeft"), value: new CIVector(biggestRect.BottomLeft)); dict.Add(key: new NSString("inputBottomRight"), value: new CIVector(biggestRect.BottomRight)); // Create a semi-transparent CIImage which will show the detected rectangle. using (var overlayCIImage = new CIImage(color: CIColor.FromRgba(red: 1.0f, green: 0f, blue: 0f, alpha: 0.5f)) // Size it to the source image. .ImageByCroppingToRect(inputCIImage.Extent) // Apply perspective distortion to the overlay rectangle to map it to the current camera picture. .CreateByFiltering("CIPerspectiveTransformWithExtent", dict) // Place overlay on the image. .CreateByCompositingOverImage(inputCIImage)) { // Must convert the CIImage into a CGImage and from there into a UIImage. // Could go directly from CIImage to UIImage but when assigning the result to a UIImageView, the ContentMode of // the image view will be ignored and no proper aspect scaling will take place. using (var ctx = CIContext.FromOptions(null)) using (CGImage convertedCGImage = ctx.CreateCGImage(overlayCIImage, overlayCIImage.Extent)) // This crashes with Xamarin.iOS //using(UIImage convertedUIImage = UIImage.FromImage(convertedCGImage, 1f, UIApplication.SharedApplication.StatusBarOrientation == UIInterfaceOrientation.LandscapeLeft ? UIImageOrientation.DownMirrored : UIImageOrientation.UpMirrored)) // This works. using (UIImage convertedUIImage = UIImage.FromImage(convertedCGImage)) { // Show converted image in UI. this.imageViewOverlay.Image = convertedUIImage; } } } // Apply a perspective correction with CIPerspectiveCorrection to the detected rectangle and display in another UIImageView. using (var dict = new NSMutableDictionary()) { dict.Add(key: new NSString("inputTopLeft"), value: new CIVector(biggestRect.TopLeft)); dict.Add(key: new NSString("inputTopRight"), value: new CIVector(biggestRect.TopRight)); dict.Add(key: new NSString("inputBottomLeft"), value: new CIVector(biggestRect.BottomLeft)); dict.Add(key: new NSString("inputBottomRight"), value: new CIVector(biggestRect.BottomRight)); // Use again CIImage -> CGImage -> UIImage to prevent scaling issues (see above). using (var perspectiveCorrectedImage = inputCIImage.CreateByFiltering("CIPerspectiveCorrection", dict)) using (var ctx = CIContext.FromOptions(null)) using (CGImage convertedCGImage = ctx.CreateCGImage(perspectiveCorrectedImage, perspectiveCorrectedImage.Extent)) using (UIImage convertedUIImage = UIImage.FromImage(convertedCGImage)) { this.imageViewPerspective.Image = convertedUIImage; } } }); } Console.WriteLine("---------------------"); }
protected override void ProcessRecord() { base.ProcessRecord(); base.WriteVerbose("Plugin Registration intiated"); FileInfo assemblyInfo = new FileInfo(AssemblyPath); var lastIndex = assemblyInfo.Name.LastIndexOf(".dll"); string assemblyName = lastIndex > 0 ? assemblyInfo.Name.Remove(lastIndex, 4) : assemblyInfo.Name; string version = FileVersionInfo.GetVersionInfo(AssemblyPath).FileVersion; string content = Convert.ToBase64String(File.ReadAllBytes(AssemblyPath)); base.WriteVerbose(string.Format("Assembly Name: {0}", assemblyName)); base.WriteVerbose(string.Format("Assembly Version: {0}", version)); using (var context = new CIContext(OrganizationService)) { PluginRegistrationHelper pluginRegistrationHelper = new PluginRegistrationHelper(OrganizationService, context); base.WriteVerbose("PluginRegistrationHelper intiated"); Assembly pluginAssembly = null; if (File.Exists(MappingJsonPath)) { base.WriteVerbose("Reading mapping json file"); string json = File.ReadAllText(MappingJsonPath); pluginAssembly = JsonConvert.DeserializeObject <Assembly>(json); base.WriteVerbose("Deserialized mapping json file"); } var pluginAssemblyId = pluginRegistrationHelper.UpsertPluginAssembly(pluginAssembly, assemblyName, version, content, SolutionName, IsWorkflowActivityAssembly, RegistrationType); base.WriteVerbose(string.Format("UpsertPluginAssembly {0} completed", pluginAssemblyId)); if (pluginAssembly != null) { // var assemblyTypes = IsWorkflowActivityAssembly ? pluginAssembly.WorkflowTypes : pluginAssembly.PluginTypes; if (pluginAssembly.PluginTypes == null) { base.WriteVerbose("No mapping found for types."); } else { foreach (var type in pluginAssembly.PluginTypes) { var pluginTypeId = pluginRegistrationHelper.UpsertPluginType(pluginAssemblyId, type, SolutionName, RegistrationType, IsWorkflowActivityAssembly, assemblyName); base.WriteVerbose(string.Format("UpsertPluginType {0} completed", pluginTypeId)); if (!IsWorkflowActivityAssembly) { foreach (var step in type.Steps) { var sdkMessageProcessingStepId = pluginRegistrationHelper.UpsertSdkMessageProcessingStep(pluginTypeId, step, SolutionName, RegistrationType); base.WriteVerbose(string.Format("UpsertSdkMessageProcessingStep {0} completed", sdkMessageProcessingStepId)); foreach (var image in step.Images) { var sdkMessageProcessingStepImageId = pluginRegistrationHelper.UpsertSdkMessageProcessingStepImage(sdkMessageProcessingStepId, image, SolutionName, RegistrationType); base.WriteVerbose(string.Format("UpsertSdkMessageProcessingStepImage {0} completed", sdkMessageProcessingStepImageId)); } } } } } } } base.WriteVerbose("Plugin Registration completed"); }
public PluginRegistrationHelper(IOrganizationService service, CIContext xrmContext, XrmCommandBase xrmCommand) { this.OrganizationService = service; this.context = xrmContext; this.xrmCommandBase = xrmCommand; }
// On load, construct the CIRawFilter public override void ViewDidLoad() { base.ViewDidLoad(); var asset = Asset; if (asset == null) { return; } // Setup options to request original image. var options = new PHImageRequestOptions { Version = PHImageRequestOptionsVersion.Original, Synchronous = true }; // Request the image data and UTI type for the image. PHImageManager.DefaultManager.RequestImageData(asset, options, (imageData, dataUTI, _, __) => { if (imageData == null || dataUTI == null) { return; } // Create a CIRawFilter from original image data. // UTI type is passed in to provide the CIRawFilter with a hint about the UTI type of the Raw file. //var rawOptions = [String (kCGImageSourceTypeIdentifierHint) : dataUTI ] var rawOptions = new NSMutableDictionary(); var imageIOLibrary = Dlfcn.dlopen("/System/Library/Frameworks/ImageIO.framework/ImageIO", 0); var key = Dlfcn.GetIntPtr(imageIOLibrary, "kCGImageSourceTypeIdentifierHint"); rawOptions.LowlevelSetObject(dataUTI, key); ciRawFilter = CIFilter.CreateRawFilter(imageData, rawOptions); if (ciRawFilter == null) { return; } // Get the native size of the image produced by the CIRawFilter. var sizeValue = ciRawFilter.ValueForKey(Keys.kCIOutputNativeSizeKey) as CIVector; if (sizeValue != null) { imageNativeSize = new CGSize(sizeValue.X, sizeValue.Y); } // Record the original value of the temperature, and setup the editing slider. var tempValue = (NSNumber)ciRawFilter.ValueForKey(Keys.kCIInputNeutralTemperatureKey); if (tempValue != null) { originalTemp = tempValue.FloatValue; TempSlider.SetValue(tempValue.FloatValue, animated: false); } // Record the original value of the tint, and setup the editing slider. var tintValue = (NSNumber)ciRawFilter.ValueForKey(Keys.kCIInputNeutralTintKey); if (tintValue != null) { originalTint = tintValue.FloatValue; TintSlider.SetValue(tintValue.FloatValue, animated: false); } }); // Create EAGL context used to render the CIImage produced by the CIRawFilter to display. ImageView.Context = new EAGLContext(EAGLRenderingAPI.OpenGLES3); ciContext = CIContext.FromContext(ImageView.Context, new CIContextOptions { CIImageFormat = CIImage.FormatRGBAh }); }
public PluginRepository(CIContext context) { this.context = context; }
protected override void ProcessRecord() { var missedWebResourcesCount = 0; var resourceFiles = new HashSet <string>(); var patterns = (string.IsNullOrWhiteSpace(SearchPattern)) ? new string[1] { "*" } : SearchPattern.Split(','); foreach (var pattern in patterns) { WriteVerbose($"Processing pattern {pattern}..."); Directory.GetFiles(Path, pattern.Trim(), SearchOption.AllDirectories).ToList() .ForEach((item) => resourceFiles.Add(item)); } if (resourceFiles.Count == 0) { WriteVerbose($"There are no files in folder '{Path}' matching patterns {SearchPattern}"); return; } else { WriteVerbose($"Found {resourceFiles.Count} resource files."); } using (var context = new CIContext(OrganizationService)) { WriteVerbose($"Retrieving web resources from CRM..."); var query = from resource in context.WebResourceSet select resource; var solutionId = GetSolutionId(context, SolutionName); if (!solutionId.Equals(Guid.Empty)) { query = from resource in context.WebResourceSet join sol in context.SolutionComponentSet on resource.Id equals sol.ObjectId where sol.SolutionId.Equals(solutionId) select resource; } var allWebResources = query.ToList(); WriteVerbose($"Found {allWebResources.Count}"); var importexportxml = new StringBuilder(); var webResource = default(WebResource); foreach (var resourceFile in resourceFiles) { WriteVerbose($"Processing file: {System.IO.Path.GetFileName(resourceFile)}"); try { webResource = allWebResources.Single(CompareCondition(resourceFile)); WriteVerbose($"Found web resource: {webResource.Name}"); } catch (Exception ex) { missedWebResourcesCount++; WriteWarning($"Cannot process {resourceFile}: {ex.Message}"); continue; } // update in context var fileContent = Convert.ToBase64String(File.ReadAllBytes(resourceFile)); if (webResource.Content?.GetHashCode() != fileContent.GetHashCode()) { webResource.Content = fileContent; //context.UpdateObject(webResource); // update web resource then add to a solution. UpdateRequest update = new UpdateRequest { Target = webResource }; update.Parameters.Add("SolutionUniqueName", SolutionName); context.Execute(update); // add id to publish xml if (Publish) { importexportxml.Append($"<webresource>{webResource.Id}</webresource>"); } } } // Update WriteVerbose("Saving changes..."); context.SaveChanges(); // Publish if (Publish) { WriteVerbose("Publishing web resources..."); PublishXmlRequest req = new PublishXmlRequest() { ParameterXml = $"<importexportxml><webresources>{importexportxml.ToString()}</webresources></importexportxml>" }; OrganizationService.Execute(req); } WriteObject($"{resourceFiles.Count - missedWebResourcesCount} out of {resourceFiles.Count} web resources were processed"); if (FailIfWebResourceNotFound && missedWebResourcesCount > 0) { ThrowTerminatingError(new ErrorRecord( new RuntimeException($"{missedWebResourcesCount} web resources were not found"), "", ErrorCategory.ObjectNotFound, null)); } } }